package ananly;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/*数据库写入线程类，记录数达到commitCharge条则提交,最后提交剩余记录*/
public class DatabaseWriter extends Thread { 
  private Connection connection;
  private SaxProcessor processor; 
  private String threadName; 
  private int commitCharge; 
  private int recordCount = 0; 

  public Connection getConnection() { 
    return connection; 
  } 

  public void setConnection(Connection connection) { 
    this.connection = connection; 
  } 

  public SaxProcessor getProcessor() { 
    return processor; 
  } 

  public void setProcessor(SaxProcessor processor) { 
    this.processor = processor; 
  } 

  DatabaseWriter(SaxProcessor processor, String threadName, 
      Connection connection) { 
    this.connection = connection; 
    this.processor = processor; 
    this.threadName = threadName; 
  } 

  public void setParameters(int commitCharge) { 
    this.commitCharge = commitCharge; 
  } 

  public void run() { 
    PreparedStatement stat = null;
    try { 
      connection.setAutoCommit(false); 
      stat = connection 
          .prepareStatement("insert  into BILL nologging values(?,?,?,?,?,?,?,?,?,?,?,?,?)");

    } catch (SQLException e1) {
      e1.printStackTrace(); 
    } 

    while (!this.processor.processingComplete()) { 
      List datas = this.processor.getNextData(this.threadName);
      System.out.println(this.threadName + " run!!"); 

      if (datas != null && stat != null) { 
        for (int i = 0; i < datas.size(); i++) { 
          try { 
            List record = (List) datas.get(i); 
            stat.setString(1,  (String) record.get(0));
            stat.setString(2,  (String) record.get(1));
            stat.setString(3,  (String) record.get(2));
            stat.setString(4,  (String) record.get(3));
            stat.setString(5,  (String) record.get(4));
            stat.setString(6,  (String) record.get(5));
            stat.setString(7,  (String) record.get(6));
            stat.setString(8,  (String) record.get(7));
            stat.setString(9,  (String) record.get(8));
            stat.setString(10, (String) record.get(9));
            stat.setString(11, (String) record.get(10));
            stat.setString(12, (String) record.get(11));
            stat.setString(13, (String) record.get(12));
            stat.execute();
            this.recordCount++; 

          } catch (SQLException e) { 
            e.printStackTrace(); 
          } 
        } 
      } 
      if (recordCount >= commitCharge) { 
        try { 
          connection.commit();
          this.recordCount = 0;
        } catch (SQLException e) { 
          e.printStackTrace(); 
        } 
      } 

    } 
    try { 
      if (!connection.isClosed()) { 
        connection.commit(); 
      } 
    } catch (SQLException e) { 
      e.printStackTrace(); 
    } 
  } 
}